import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
const moment = require('moment');

/**
 * 单一表插入前钩子
 * @param {*} record 插入前的数据
 * @param {*} options 配置参数
 */
export const singleBeforeCreate = (record, options) => {
  record.create_time = moment().format('X'); // 创建时间设置为当前

  // 记录操作历史
  record.history = [{
    time: moment().format('X'),
    operate: 'create',
    user: record.create_user_name
  }];
};

/**
 * 单一表更新前钩子
 * @param {*} record 插入前的数据
 * @param {*} options 配置参数
 * @param {*} fields 字段说明
 */
export const singleBeforeUpdate = (record, options, fields) => {
  record.modify_time = moment().format('X'); // 修改时间设置为当前

  // 获取更新前的记录数据（原始数据）
  const originalData = record._previousDataValues;
  // 获取更新后的数据（即将保存的数据）
  const updatedData = record.dataValues;

  // 对比新旧数据
  const change = [];
  for (const key in updatedData) {
    if (['create_time', 'create_user_id', 'create_user_name', 'modify_time', 'modify_user_id', 'modify_user_name', 'history', 'uid'].includes(key)) continue;

    let oldValue = originalData[key];
    let newValue = updatedData[key];

    if (oldValue === undefined || newValue === undefined) continue;

    // 数值型转成数字再对比
    if (['BIGINT', 'INTEGER', 'DECIMAL'].includes(fields[key].type.key)) {
      oldValue = Number(oldValue);
      newValue = Number(newValue);
    } else if (['JSON'].includes(fields[key].type.key)) { // JSON类型转成字符串再对比
      if (typeof oldValue === 'object') oldValue = JSON.stringify(oldValue);
      if (typeof newValue === 'object') newValue = JSON.stringify(newValue);
    }

    if (oldValue !== newValue) {
      change.push({
        field: key,
        oldValue: originalData[key],
        newValue: updatedData[key],
        comment: fields[key].comment
      });
    }
  }
  // console.log('hook', change);
  if (change.length > 0) {
    const item = {
      time: moment().format('X'),
      operate: 'update',
      user: record.modify_user_name,
      change
    };
    record.history = [...record.dataValues.history, item];
  }
}
